<template>
  <div class="app-container">
    <!--    搜索内容-->
    <el-form
      ref="searchForm"
      :inline="true"
      :model="params"
      class="demo-form-inline"
    >
      <el-form-item label="名称" prop="name">
        <el-input
          v-model="params.name"
          clearable
          placeholder="请输入会员名字"
        />
      </el-form-item>
      <el-form-item label="店铺名称">
        <el-select v-model="params.belongingStoreId" placeholder="请选择店铺">
          <el-option v-for="item in shops" :key="item.belongingStoreId" :label="item.name" :value="item.belongingStoreId" />
        </el-select>
      </el-form-item>
      <el-form-item label="会员等级">

        <el-select v-model="params.gradeId" placeholder="请选择会员等级">
          <!--          <el-option v-for="item in shops" :key="item.belongingStoreId" :label="item.name" :value="item.belongingStoreId" />-->
          <el-option v-for="item in gradeList" :key="item.gradeId" :label="item.gradeName" :value="item.gradeId" />
        </el-select>

      </el-form-item>
      <el-button type="primary" plain icon="el-icon-search" @click="searchEmp()">搜索</el-button>
      <el-button
        type="primary"
        icon="el-icon-refresh"
        plain
        @click="resetSearchForm()"
      >
        重置
      </el-button>
      <!--&lt;!&ndash;            <el-button type="primary" @click="handleAdd()">新增</el-button>&ndash;&gt;-->
      <el-button type="primary" plain icon="el-icon-plus" @click="onAddQuestion">新增会员</el-button>
      <!--表头数据 -->
    </el-form>
    <el-table
      :data="memberList"
      element-loading-text="Loading"
      border
      fit
      highlight-current-row
      stripe
      style="width: 100%; margin-top: 10px"
      :cell-style="cellStyle"
      :header-cell-style="headStyle"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column prop="memberId" label="会员ID" width="120" />
      <el-table-column label="会员头像" width="200" prop="imageUrl">
<!--          <template v-slot:default="scope">-->
<!--            <img class="imgBg" :src="scope.row.imageUrl" alt=""  style= "width: 80px;height:80px;border-radius: 50px">-->
<!--          </template>-->
        <template #default="{ row }">
          <img class="imgBg" :src="row.imageUrl" alt=""  style= "width: 80px;height:80px;border-radius: 50px">
        </template>
      </el-table-column>
<!--      <el-table-column  label="用户头像">-->
<!--        <template slot-scope="props">-->
<!--          <el-form label-position="left" inline class="demo-table-expand">-->
<!--            <el-form-item style="margin-top:10px;">-->
<!--              <img v-image-preview :src="url" width="100" height="100">-->
<!--            </el-form-item>-->
<!--          </el-form>-->
<!--        </template>-->

<!--      </el-table-column>-->
      <el-table-column prop="name" label="名称" width="180" />
      <el-table-column prop="gradeName" label="会员等级" width="150" />
      <el-table-column prop="phone" label="手机号" width="180" />
      <el-table-column prop="shopName" label="所属店铺" width="180" />
      <el-table-column prop="balance" label="积分" width="140" />

      <el-table-column prop="createTime" label="创建时间" width="180" />
      <el-table-column label="操作" fixed="right" width="200px">
        <template #default="{ row }">
          <!--          <el-button size="mini" @click="handleEdit(row.memberId)">编辑</el-button>-->
          <!--          <el-button size="mini" type="danger" @click="handleDelete(row.memberId)">删除</el-button>-->
          <el-button class="red" type="text" @click="onEdit(row.memberId)">编辑
          </el-button>
          <el-button type="text" icon="el-icon-delete" @click="onDelete(row.memberId)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      background
      :current-page="params.pageNum"
      :page-sizes="[5, 10, 15, 20]"
      :page-size="params.pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      style="margin-top: 20px; justify-content: flex-end"
      class="pagination-container"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
    <el-drawer
      :visible.sync="drawer"
      :direction="direction"
      :before-close="handleClose"
      size="50%"
    >
      <el-form :model="fromMember" label-width="100px">
        <el-form-item label="会员名称: ">
          <el-input v-model="fromMember.name" style="width: 387px !important" placeholder="请输入会员名字" />
        </el-form-item>

        <el-form-item label="手机号: ">
          <el-input v-model="fromMember.phone" style="width: 387px !important" placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item label="选择店铺: ">
          <el-select v-model="fromMember.belongingStoreId" placeholder="请选择店铺">
            <el-option v-for="item in shops" :key="item.belongingStoreId" :label="item.name" :value="item.belongingStoreId" />
          </el-select>
        </el-form-item>
        <el-form-item label="选择店铺: ">
          <el-select v-model="fromMember.gradeId" placeholder="请选择会员等级">
            <!--          <el-option v-for="item in shops" :key="item.belongingStoreId" :label="item.name" :value="item.belongingStoreId" />-->
            <el-option v-for="item in gradeList" :key="item.gradeId" :label="item.gradeName" :value="item.gradeId" />
          </el-select>
        </el-form-item>
        <el-form-item label="金额: ">
          <el-input-number v-model="fromMember.balance" :min="1" :max="1000" @change="handleChange" />
        </el-form-item>
        <div v-show="!fromMember.memberId">
          <el-form-item label="上传图片: ">
            <el-upload
              class="avatar-uploader"
              action=""
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
              :http-request="upload"
            >

              <img v-if="imageUrl" :src="imageUrl" class="avatar">
              <i v-else class="el-icon-plus avatar-uploader-icon" />
            </el-upload>
          </el-form-item>
        </div>
<!--        <el-form-item label="上传图片: ">-->
<!--          <el-upload-->
<!--            class="avatar-uploader"-->
<!--            action=""-->
<!--            :show-file-list="false"-->
<!--            :on-success="handleAvatarSuccess"-->
<!--            :before-upload="beforeAvatarUpload"-->
<!--            :http-request="upload"-->
<!--          >-->

<!--            <img v-if="imageUrl" :src="imageUrl" class="avatar">-->
<!--            <i v-else class="el-icon-plus avatar-uploader-icon" />-->
<!--          </el-upload>-->
<!--        </el-form-item>-->
        <el-form-item>
          <el-button class="question-button" type="primary" plain @click="onSubmit()">发布</el-button>
        </el-form-item>
      </el-form>

    </el-drawer>
<!--    <el-image-->
<!--      style="width: 100px; height: 100px"-->
<!--      :src="url"-->
<!--      :fit="fit"></el-image>-->
  </div>
</template>
<script>
import {
  addMemberService,
  deleteMemBerService,
  getMemberDetailService,
  getMemberService,
  updateMemBerService
} from '@/api/vip/member'
import { getShops } from '@/api/shopList'
import { getGrageListService } from '@/api/vip/Grade'
import COS from 'cos-js-sdk-v5'
// 引入 nanoid
import { nanoid } from 'nanoid'

export default {
  data() {
    return {
      memberList: [],
      total: 0,
      params: {
        pageNum: 1,
        pageSize: 5,
        name: '',
        belongingStoreId: '',
        gradeId: ''
      },
      shops: [],
      gradeList: [],
      drawer: false,
      fromMember: {
        memberId: '',
        name: '',
        phone: '',
        gradeId: '',
        belongingStoreId: '',
        balance: '',
        imageUrl: ''
      },
      imageUrl: ''
    }
  },
  created() {
    this.getmemberList()
    this.getShops()
    this.getGrageList()
    this.add()
  },
  methods: {
    add() {
      console.log('生成唯一的Id', this.imageUid)
      const uuid = `${nanoid()}.jpg`
      console.log('生成唯一的Id', uuid)
    },
    cellStyle({ row, column, rowIndex, columnIndex }) {
      return { 'text-align': 'center' }
    },
    headStyle() {
      return 'text-align: center'
    },
    resetSearchForm() {
      this.params.name = ''
      this.params.gradeId = ''
      this.params.belongingStoreId = ''
      this.params.pageNum = 1
      this.getmemberList()
    },
    getmemberList() {
      getMemberService(this.params).then(
        (ret) => {
          this.memberList = ret.data.list
          this.imageUrlDTO = ret.data.list
          this.total = ret.data.total
        }
      )
    },
    handleSizeChange(val) {
      this.params.pageSize = val
      this.params.pageNum = 1
      this.getmemberList()
    },
    handleCurrentChange(val) {
      this.params.pageNum = val
      this.getmemberList()
    },
    getShops() {
      getShops().then(
        (ret) => {
          this.shops = ret.data
        })
    },
    searchEmp() {
      this.params.pageNum = 1
      this.getmemberList()
    },
    getGrageList() {
      getGrageListService().then(
        (ret) => {
          this.gradeList = ret.data
        }
      )
    },
    handleAvatarSuccess(res, file) {
      this.imageUrl = URL.createObjectURL(file.raw)
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },
    validate() {
      let msg = ''
      if (!this.fromMember.name) {
        msg = '请添加会员名称'
      } else if (!this.fromMember.phone) {
        msg = '请添加手机号'
      } else if (this.fromMember.belongingStoreId == '') {
        msg = '请选择店铺'
      } else if (this.fromMember.gradeId == '') {
        msg = '请选择会员等级'
      } else {
        msg = ''
      }
      return msg
    },
    onAddQuestion() {
      this.fromMember = {}
      this.drawer = true
    },
    onEdit(memberId) {
      this.fromMember = {}
      this.drawer = true
      getMemberDetailService(memberId).then(
        (ret) => {
          this.fromMember = ret.data
          // this.imageUrl = ret.data.imageUrl
          console.log(this.fromMember.memberId)
        }
      )
    },
    onDelete(memberId) {
      deleteMemBerService(memberId).then(
        (ret) => {
          this.$message.success('删除成功')
          this.params.pageNum = 1
          this.getmemberList()
        }
      )
    },
    onSubmit() {
      const errMessage = this.validate()
      if (errMessage) {
        this.$message.error(errMessage)
        return false
      }
      if (this.fromMember.memberId) {
        updateMemBerService(this.fromMember).then(
          (ret) => {
            this.$message.success('修改成功')
            this.drawer = false
            this.params.pageNum = 1
            this.getmemberList()
          }
        )
      } else {
        addMemberService(this.fromMember).then(
          (ret) => {
            this.$message.success('添加成功')
            this.drawer = false
            this.params.pageNum = 1
            this.getmemberList()
          }
        )
      }
    },
    // 上传到对象cos
    upload(params) {
      const imageKey = `${nanoid()}.jpg`
      const cos = new COS({
        // 密钥
        SecretId: 'AKID8GLNDsQkx1xiJitEMI0TjqkT3TikZFj2',
        SecretKey: 'znNlvsa4JJ4bt77tRkodHivteBmBLJ3a'
      })
      cos.putObject({
        Bucket: 'wyztest-1314621397',
        Region: 'ap-nanjing',
        Key: imageKey,
        Body: params.file,
        onProgress: function(progressData) {
          console.log(JSON.stringify(progressData))
        }
      },
      (err, data) => {
        console.log(err || data)
        if (data) {
          console.log('上传图片路径', data.Location)
          this.imageUrl = 'https://' + data.Location
          this.fromMember.imageUrl = 'https://' + data.Location
          // 通知父亲
          this.$emit('input', 'https://' + data.Location)
        }
      })
    }
  }
}
</script>
<style>
.pagination-container {
  text-align: center;
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}

</style>
